package de.dopichaj.labrador.index.backend;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

import de.dopichaj.labrador.util.io.BitInputStream;
import de.dopichaj.labrador.util.io.BitOutputStream;
import de.dopichaj.labrador.util.io.ByteReader;
import de.dopichaj.labrador.util.io.ByteWriter;
import de.dopichaj.labrador.util.io.DataInputToByteReaderAdapter;


public final class Dictionary implements Iterable<String>, ReadOnlyDictionary {
    
    public static final int BLOCK_SIZE = 100;
    private final Map<String, Term> dictionary = new HashMap<String, Term>();
    private final Map<Integer, Term> reverseDictionary = new HashMap<Integer, Term>();
    private int maxID = 0;
    
    /* (non-Javadoc)
     * @see de.dopichaj.labrador.index.backend.ReadOnlyDictionary#getTerm(java.lang.String)
     */
    public Term getTerm(final String text) {
        final Term term;
        if (containsTerm(text)) {
            term = dictionary.get(text);
        } else {
            term = getNewTerm(text);
        }
        return term;
    }
    
    public boolean containsTerm(final String text) {
        return dictionary.containsKey(text);
    }

    public Term getTerm(final int id) {
        assert reverseDictionary.containsKey(id);
        return reverseDictionary.get(id);
    }
   
    private Term getNewTerm(final String text) {
        final Term term;
        term = new Term(maxID, text, 0, 0, 0);
        dictionary.put(text, term);
        reverseDictionary.put(maxID, term);
        maxID++;
        return term;
    }
   
    public void setIndexPosition(final int termID, final int indexPosition) {
        getTerm(termID).setIndexPosition(indexPosition);
    }

    public void write(final DataOutput stream) throws IOException {
        
        final BitOutputStream output = new BitOutputStream(new ByteWriter(stream, 1024));
        
        // sort the dictionary by term string
        final SortedSet<String> terms = new TreeSet<String>(dictionary.keySet());
        
        output.writeVariableLengthInt(dictionary.size());
        
        // write the blocks
        int blockPos = 0;
        for (final String termString : terms) {
        
            final Term term = dictionary.get(termString);

            // write the term data
            output.writeVariableLengthInt(term.getID());
            output.writeString(termString);
            output.writeVariableLengthInt(term.getElementFrequency());
            output.writeVariableLengthInt(term.getDocumentFrequency());
            output.writeVariableLengthInt(term.getCollectionFrequency());
            output.writeBits(term.getIndexPosition(), 31);
            
            // advance the block position
            blockPos++;
            if (blockPos == BLOCK_SIZE) {
                blockPos = 0;
                output.flush();
            }
        }
        
        // pad the last block to the block size
        for (; blockPos < BLOCK_SIZE; blockPos++) {
            output.writeVariableLengthInt(0);
            output.writeString("x");
            output.writeVariableLengthInt(0);
            output.writeVariableLengthInt(0);
            output.writeVariableLengthInt(0);
            output.writeBits(0, 31);
        }
        
        output.close();
    }
    
    public void read(final ByteReader stream) throws IOException {
        
        final BitInputStream input = new BitInputStream(stream);
        final int count = input.readVariableLengthInt();
        for (int i = 0; i < count; i++) {
            
            if (i % BLOCK_SIZE == 0) {
                input.skipToNext();
            }
            
            final int termID = input.readVariableLengthInt();
            
            final String text = input.readString();
            final int elementFrequency = input.readVariableLengthInt();
            final int documentFrequency = input.readVariableLengthInt();
            final int collectionFrequency = input.readVariableLengthInt();
            final Term term = new Term(termID, text, elementFrequency,
                documentFrequency, collectionFrequency);
            final int indexPos = input.readBits(31);
            term.setIndexPosition(indexPos);
            dictionary.put(text, term);
        }
    }
    
    public void read(final DataInput input) throws IOException {
        
        read(new DataInputToByteReaderAdapter(input));
    }
    
    public Iterator<String> iterator() {
        return dictionary.keySet().iterator();
    }
}
/*
Copyright (c) 2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/